<?php

// $Id$

require_once('../../boot.inc.php');
boot('my_site');

global $WSC;


require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/settings/tcms_settings_sitemap_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/sitemap/tcms_sitemap_generator.class.php');


global $_SITE_DBC;
if (!($_SITE_DBC instanceof DB_Connection)) {
	$db_config_loader = new DB_Config_Loader_File($PATHS->get_hidden().'conf/db.conf');
	$db_config = new DB_Config();
	$db_config_loader->load_db_config($db_config);
	$_SITE_DBC = new Site_DBC($db_config);
}
$dbc = $_SITE_DBC;


session_start();

$context = new Web_Context();

$settings_sitemap = new TCMS_Settings_Sitemap_DBC();
if ($settings_sitemap->load_by_id($dbc, 1)) {
	if ($settings_sitemap->get_mode() == 0) { //if manual
		$filename = $WSC->get_scratch_dir().TCMS_Sitemap_Generator::SITEMAP_FILE;
		if (file_exists($filename)) {
			generate_sitemap_file($dbc, $WSC, $context);
			output_sitemap_file($WSC);
		} else {
			output_sitemap_file($WSC);
		}
	} else {
		generate_sitemap_file($dbc, $WSC, $context);
		output_sitemap_file($WSC);
	}
} else {
	throw new Tangra_Module_Exception('Cannot load settings sitemap');
}


function output_sitemap_file(Web_Site_Config $WSC) {
	$filename = $WSC->get_scratch_dir().TCMS_Sitemap_Generator::SITEMAP_FILE;

	if (file_exists($filename)) {
		$timestamp = filemtime($filename);
		$gmt_mtime = gmdate('D, d M Y H:i:s', $timestamp) . ' GMT';
		header("Last-Modified: " . $gmt_mtime);

		header("Cache-Control: public, must-revalidate");
		header("Content-Type: application/xml");
		header("Content-Length: " .(string)(filesize($filename)) );
		header("Content-Transfer-Encoding: binary\n");
		readfile($filename);
	}
}


function generate_sitemap_file(DB_Connection $dbc, Web_Site_Config $WSC, Web_Context $context) {
	$prefix = prepare_prefix($WSC, $context);
	$tple = new Tple();
	TCMS_Sitemap_Generator::generate($dbc, $tple, $WSC->get_scratch_dir(), $prefix);
}


function prepare_prefix(Web_Site_Config $WSC, Web_Context $context) {
	if ($context->exists_in_server('HTTPS')) {
		$https = $context->get_from_server('HTTPS');
	} else {
		$https = false;
	}
	$protocol = ($https) ? 'https' : 'http';


	$ret = $protocol.'://'.$context->get_from_server('SERVER_NAME');;
	if ( $context->get_from_server('SERVER_PORT') &&  $context->get_from_server('SERVER_PORT') != '80') {
		$ret .= ':'. $context->get_from_server('SERVER_PORT');
	}
	$ret .= '/';
	return $ret;
}